<?php

namespace App\Console\Commands;

use App\Models\Company;
use App\Models\Group;
use App\Models\Admin;
use App\Services\HelpService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;

class CreateUser extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'user:create';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Create user through csv.';

    //表格目录
    private $excel_url = 'user/excel';
    //临时目录
    private $temp_url = 'user/temp';
    //错误日志
    private $err_url = 'user/err';
    //用户密码信息
    private $user_pwd = [];
    //错误信息
    private $error = [];


    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
        //检查临时目录和json保存目录是否存在
        if(!file_exists(storage_path('user'))) {
            mkdir(storage_path('user'));
        }
        if(!file_exists(storage_path($this->temp_url))) {
            mkdir(storage_path($this->temp_url));
        }
        if(!file_exists(storage_path($this->err_url))) {
            mkdir(storage_path($this->err_url));
        }
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $url = storage_path($this->excel_url);
        if (!is_dir($url)) {
            return $this->error('导入用户文件夹不存在');
        }
        if (false !== ($url = opendir($url))) {
            $i = 1;
            while ($excel = readdir($url)) {
                if ($excel != "." && $excel != "..") {
                    //excel信息封装
                    $this->readExcel($excel, $i);
                    //数据保存
                    ++$i;
                }
            }
            //将密码保存为
            $this->writeExcel($this->user_pwd, ['name', 'email', 'pwd'], 'user/');
            $this->writeExcel($this->error, [
                'name',
                'mobile',
                'email',
                'position',
                'type',
                'group',
                'company',
                'err',
            ], $this->err_url . '/');
            HelpService::deleteDir(storage_path($this->temp_url));
        }
    }

    private function readExcel($file, $i) {
        //中文名xlsx无法打开，重命名保存临时文件在tamp目录
        copy(storage_path($this->excel_url.'/'.$file),
            storage_path($this->temp_url.'/'.$i.'.csv'));
        $obj_reader =  new \PHPExcel_Reader_CSV();
        $obj_reader = $obj_reader
            ->setDelimiter(',')
            ->setInputEncoding('GBK')
            ->setSheetIndex(0);

        $obj_excel = $obj_reader->load(storage_path($this->temp_url.'/'.$i.'.csv'));
        $sheet = $obj_excel->getSheet(0);
        $row_count = $sheet->getHighestRow();
        for ($j=2; $j <= $row_count; ++$j) {
            $user = new User();
            $info['name'] = trim($sheet->getCell("A$j")->getValue());
            $info['mobile'] = trim($sheet->getCell("B$j")->getValue());
            $info['email'] = trim($sheet->getCell("C$j")->getValue());
            $info['position'] = trim($sheet->getCell("D$j")->getValue());
            $info['type'] = trim($sheet->getCell("E$j")->getValue());
            $info['group'] = trim($sheet->getCell("F$j")->getValue());
            $info['company'] = trim($sheet->getCell("G$j")->getValue());
            //用户权限
            if($info['type'] === '管理员') {
                $user->groupRole = 2;
            } else if ($info['type'] === '操作员') {
                $user->groupRole = 3;
            } else {
                $this->errorMessage($info, '用户类型错误');
                continue;
            }
            $user->role = 2;
            //用户名
            $user->name = $info['name'];
            //邮箱：唯一
            $has_email = User::where('email', $info['email'])
                ->count();
            if (!$has_email) {
                $user->email = $info['email'];
            } else {
                $this->errorMessage($info, '该邮箱已存在');
                continue;
            }
            //手机号：唯一
//            $has_mobile = User::where('mobile', $info['mobile'])
//                ->count();
//            if (!$has_mobile) {
//                $user->mobile = $info['mobile'];
//            } else {
//                $this->errorMessage($info, '该手机号已存在');
//                continue;
//            }
            //职位
            $user->position = $info['position'];
            //随机密码
            $randomPwd = HelpService::createRandomStr(6);
            $user->password = bcrypt($randomPwd);
            //公司id
            $company_name = $info['company'];
            $company = Company::where('name', $company_name)->first();
            if($company) {
                $user->company_id = $company->id;
            } else {
                $this->errorMessage($info, '公司名称不存在');
                continue;
            }
            //业务线id：仅业务管理员有此字段
            if ($user->groupRole === 2) {
                $groups = mb_split('/', $info['group']);
                $parent_id = '';
                $count = count($groups);
                $num = 0;
                while ($count) {
                    $group = Group::where([
                        'name' => $groups[$num],
                        'parent_id' => $parent_id,
                        'com_key' => $user->company_id,
                    ])->first();
                    --$count;
                    ++$num;
                    if ($group) {
                        $parent_id = $group->id;
                    } else {
                        $this->errorMessage($info, '业务线有误');
                        continue 2;
                    }
                }
                $user->group_id = $parent_id;
            } else {
                $user->group_id = '';
            }
            $user->save();
            Log::useFiles(storage_path('logs/pwd.txt', 'debug'));
            Log::info('['.$user->id.'] create password: ('.$randomPwd.') of ('.$user->name.')');
            $this->user_pwd[] = [
                'name' => $user->name,
                'email' => $user->email,
                'pwd' => $randomPwd,
            ];
        }
    }

    private function writeExcel($inputValue, $title, $path) {
        if ($inputValue) {
            $obj_excel = new \PHPExcel();
            $obj_write =  new \PHPExcel_Writer_CSV($obj_excel);
            $obj_excel->setActiveSheetIndex(0);
            for ($i = 0; $i < count($title); ++$i) {
                $label = HelpService::letterOperate('A', '+', $i);
                $obj_excel->getActiveSheet()->setCellValue($label . '1', $title[$i]);
                foreach ($inputValue as $key => $value) {
                    $j = $key + 2;
                    $obj_excel->getActiveSheet()->setCellValue("{$label}$j", $value[$title[$i]]);
                }
            }

            $j = 1;
            $fileName = '';
            while ($j) {
                $fileName = date('Y-m-d') . '_' . $j . '.csv';
                if (file_exists(storage_path($path . $fileName))) {
                    ++$j;
                } else {
                    break;
                }
            }
            $obj_write->save(storage_path($path . $fileName));
        }
    }

    private function errorMessage($info, $error_message) {
        $info['err'] = $error_message;
        $this->error[] = $info;
    }
}
